<?php

declare(strict_types=1);

namespace app\common\controller;

use app\admin\controller\device\updata;
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;

class Mqtt
{
    // 发布数据
    public function publish($type, $data, $pub)
    {
        $connectionSettings  = new ConnectionSettings();
        $connect = $connectionSettings
            ->setUsername(env('mqtt.username'))
            ->setPassword(env('mqtt.password'))
            ->setConnectTimeout(60)
            ->setSocketTimeout(5)
            ->setResendTimeout(10)
            ->setKeepAliveInterval(10)
            ->setLastWillTopic(null)
            ->setLastWillMessage(null)
            ->setLastWillQualityOfService(0)
            ->setRetainLastWill(false)
            ->setUseTls(false)
            ->setTlsVerifyPeer(true)
            ->setTlsVerifyPeerName(true)
            ->setTlsSelfSignedAllowed(false)
            ->setTlsCertificateAuthorityFile(null)
            ->setTlsCertificateAuthorityPath(null)
            ->setTlsClientCertificateFile(null)
            ->setTlsClientCertificateKeyFile(null)
            ->setTlsClientCertificateKeyPassphrase(null);
        $mqtt = new MqttClient(env('mqtt.host'), (int)env('mqtt.port'), "GnssServicePub");
        $mqtt->connect($connect, false);
        $payload = array(
            'type' => $type,
            'value' => $data
        );
        $mqtt->publish(
            // topic
            "/gnss/sub/" . $pub,
            // payload
            json_encode($payload),
            // qos
            1,
            // retain
            true
        );
    }

    // 解析数据
    public function analysis($data)
    {
        if (empty($data)) {
            print("数据为空\r\n");
        } else {
            $analysis = json_decode($data, true);
            switch ($analysis['type']) {
                case "Online":
                    // 设备上线-终端沉默期为12小时，该项不适用
                    break;
                case "Offline":
                    // 设备下线-终端沉默期为12小时，该项不适用
                    break;
                case "gps":
                    // 上报gps数据
                    $updata = new updata();
                    $updata->index($data, $analysis['imei'], $analysis['gps'], $analysis['v'], $analysis['t']);
                    break;
                default:
                    // code...
                    print("未知情况\r\n");
            }
        }
    }
}
